using Microsoft.AspNetCore.Mvc;
using GroupSix.Application.Services;
using GroupSix.Application.Dtos;
using GroupSix.Domain.Entity.App;

namespace GroupSix.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly UserService _userService;

    public UserController(UserService userService)
    {
        _userService = userService;
    }

    /// <summary>
    /// 获取用户个人信息
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>用户个人信息</returns>
    [HttpGet("profile/{userId}")]
    public async Task<IActionResult> GetUserProfile(Guid userId)
    {
        try
        {
            var profile = await _userService.GetUserProfileAsync(userId);
            return Ok(new { success = true, data = profile, message = "获取用户信息成功" });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"获取用户信息失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 更新用户个人信息
    /// </summary>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut("profile")]
    public async Task<IActionResult> UpdateUserProfile([FromBody] UpdateUserProfileRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();
                
                return BadRequest(new { 
                    success = false, 
                    message = "输入验证失败", 
                    errors = errors 
                });
            }

            var response = await _userService.UpdateUserProfileAsync(request);
            return Ok(new { success = true, data = response, message = response.Message });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"更新用户信息失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取当前用户信息（兼容旧版本）
    /// </summary>
    /// <returns>用户信息</returns>
    [HttpGet("profile")]
    public async Task<IActionResult> GetProfile()
    {
        try
        {
            // 这里应该从JWT Token中获取用户信息
            // 暂时使用固定的admin用户ID，后续可以从Token中解析用户ID
            var adminUserId = Guid.Parse("44444444-4444-4444-4444-444444444444");
            var profile = await _userService.GetUserProfileAsync(adminUserId);
            
            return Ok(new { success = true, data = profile });
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { success = false, message = ex.Message });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"获取用户信息失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>用户列表</returns>
    [HttpGet("list")]
    public async Task<IActionResult> GetUserList([FromQuery] GetUserListRequestDto request)
    {
        try
        {
            var (success, message, data) = await _userService.GetUserListAsync(request);
            if (success)
            {
                return Ok(new { success = true, data = data, message = message });
            }
            else
            {
                return BadRequest(new { success = false, message = message });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"获取用户列表失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();
                
                return BadRequest(new { 
                    success = false, 
                    message = "输入验证失败", 
                    errors = errors 
                });
            }

            var (success, message, data) = await _userService.CreateUserAsync(request);
            if (success)
            {
                return Ok(new { success = true, data = data, message = message });
            }
            else
            {
                return BadRequest(new { success = false, message = message });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"创建用户失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="request">更新请求</param>
    /// <returns>更新结果</returns>
    [HttpPut]
    public async Task<IActionResult> UpdateUser([FromBody] UpdateUserRequestDto request)
    {
        try
        {
            // 验证模型状态
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();
                
                return BadRequest(new { 
                    success = false, 
                    message = "输入验证失败", 
                    errors = errors 
                });
            }

            var (success, message, data) = await _userService.UpdateUserAsync(request);
            if (success)
            {
                return Ok(new { success = true, data = data, message = message });
            }
            else
            {
                return BadRequest(new { success = false, message = message });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"更新用户失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteUser(Guid id)
    {
        try
        {
            var (success, message) = await _userService.DeleteUserAsync(id);
            if (success)
            {
                return Ok(new { success = true, message = message });
            }
            else
            {
                return BadRequest(new { success = false, message = message });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"删除用户失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 切换用户状态
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="status">新状态</param>
    /// <returns>操作结果</returns>
    [HttpPut("{id}/status")]
    public async Task<IActionResult> ToggleUserStatus(Guid id, [FromBody] ToggleUserStatusRequestDto request)
    {
        try
        {
            var (success, message) = await _userService.ToggleUserStatusAsync(id, request.Status);
            if (success)
            {
                return Ok(new { success = true, message = message });
            }
            else
            {
                return BadRequest(new { success = false, message = message });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = $"切换用户状态失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 健康检查
    /// </summary>
    /// <returns>服务状态</returns>
    [HttpGet("health")]
    public IActionResult Health()
    {
        return Ok(new { 
            success = true, 
            message = "API服务运行正常",
            timestamp = DateTime.UtcNow,
            version = "1.0.0"
        });
    }
} 